// customize.js
const app = getApp()
const http = require('../../utils/http.js')
const config = require('../../utils/config.js')

Page({
  data: {
    config,
    avatarId: null,
    faceBaseUrl: '', // 头像底图URL
    faceName: '基础脸型', // 头像名称
    currentLayer: 'hair', // 当前选中的图层
    isFromDraft: false, // 是否从草稿编辑进来
    currentDraftId: null, // 当前编辑的草稿ID
    draftName: '', // 草稿名称
    layers: {
      hair: [],
      eyes: [],
      eyesRight: [],
      eyebrows: [],
      eyebrowsRight: [],
      mouth: [],
      blush: [],
      blushRight: []
    },
    selectedElements: {
      hair: null,
      eyes: null,
      eyesRight: null,
      eyebrows: null,
      eyebrowsRight: null,
      mouth: null,
      blush: null,
      blushRight: null
    },
    showPreview: false,
    currentZoom: 1,
    loading: false,
    // 五官资源分页参数
    currentPage: 1,
    pageSize: 10,
    // 图层类型映射
    layerTypeMap: {
      hair: 8, // 发型
      eyes: 1, // 左眼
      eyesRight: 2, // 右眼
      eyebrows: 3, // 左眉
      eyebrowsRight: 4, // 右眉
      blush: 5, // 左腮红
      blushRight: 6, // 右腮红
      mouth: 7 // 嘴巴
    },
    // 拖拽缩放相关数据
    editMode: false, // 是否处于编辑模式
    currentEditingLayer: null, // 当前编辑的图层
    panelCollapsed: false, // 精细控制面板是否收起
    // 图层位置数据 - 相对于face-container的绝对坐标
    // face-container现在固定为310x430，基础头像280x280居中，中心点为(155, 215)
    layerPositions: {
      hair: { x: 155, y: 180 }, // 头发
      eyebrows: { x: 125, y: 185 }, // 左眉
      eyebrowsRight: { x: 185, y: 185 }, // 右眉
      eyes: { x: 125, y: 215 }, // 左眼
      eyesRight: { x: 185, y: 215 }, // 右眼
      blush: { x: 115, y: 245 }, // 左腮红
      blushRight: { x: 195, y: 245 }, // 右腮红
      mouth: { x: 155, y: 275 } // 嘴巴
    },
    // 各图层的缩放和旋转
    layerTransforms: {
      hair: { scale: 1, rotation: 0 },
      eyes: { scale: 1, rotation: 0 }, // 左眼
      eyesRight: { scale: 1, rotation: 0 }, // 右眼
      eyebrows: { scale: 1, rotation: 0 }, // 左眉
      eyebrowsRight: { scale: 1, rotation: 0 }, // 右眉
      mouth: { scale: 1, rotation: 0 },
      blush: { scale: 1, rotation: 0 }, // 左腮红
      blushRight: { scale: 1, rotation: 0 } // 右腮红
    },
    shareImageUrl: '', // 分享图片URL
    // 控制点位置 - 相对于face-container的绝对坐标
    // face-container现在固定为310x430，基础头像280x280居中，中心点为(155, 215)
    controlPoints: {
      hair: {
        center: { x: 155, y: 100 },
        scale: { x: 205, y: 100 },
        rotate: { x: 155, y: 30 },
        cancel: { x: 105, y: 100 }
      },
      eyes: {
        center: { x: 125, y: 215 }, // 左眼
        scale: { x: 175, y: 215 },
        rotate: { x: 125, y: 145 },
        cancel: { x: 75, y: 215 }
      },
      eyesRight: {
        center: { x: 185, y: 215 }, // 右眼
        scale: { x: 235, y: 215 },
        rotate: { x: 185, y: 145 },
        cancel: { x: 135, y: 215 }
      },
      eyebrows: {
        center: { x: 125, y: 185 }, // 左眉
        scale: { x: 175, y: 185 },
        rotate: { x: 125, y: 115 },
        cancel: { x: 75, y: 185 }
      },
      eyebrowsRight: {
        center: { x: 185, y: 185 }, // 右眉
        scale: { x: 235, y: 185 },
        rotate: { x: 185, y: 115 },
        cancel: { x: 135, y: 185 }
      },
      mouth: {
        center: { x: 155, y: 275 },
        scale: { x: 205, y: 275 },
        rotate: { x: 155, y: 205 },
        cancel: { x: 105, y: 275 }
      },
      blush: {
        center: { x: 115, y: 245 }, // 左腮红
        scale: { x: 165, y: 245 },
        rotate: { x: 115, y: 175 },
        cancel: { x: 65, y: 245 }
      },
      blushRight: {
        center: { x: 195, y: 245 }, // 右腮红
        scale: { x: 245, y: 245 },
        rotate: { x: 195, y: 175 },
        cancel: { x: 145, y: 245 }
      }
    }
  },

  onLoad: function (options) {
    console.log('定制页面加载，参数:', options)

    // 检查是否有草稿ID参数
    if (options.draftId) {
      console.log('加载草稿ID:', options.draftId)
      // 设置从草稿编辑进来的标记
      this.setData({
        isFromDraft: true,
        currentDraftId: options.draftId
      })
      this.loadDraftData(options.draftId)
    } else {
      // 正常加载流程
      this.setData({
        avatarId: options.avatarId || null,
        isFromDraft: false,
        currentDraftId: null
      })

      if (this.data.avatarId) {
        this.getFaceBaseDetail(this.data.avatarId)
      }

      this.loadLayersData()
    }
  },

  // 加载草稿数据
  loadDraftData: function (draftId) {
    console.log('加载草稿ID:', draftId)
    const that = this
    that.setData({ loading: true })

    try {
      const params = {
        url: '/p/faceDraft/info',
        method: 'GET',
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          draftId: draftId
        },
        callBack: res => {
          console.log('获取草稿详情成功:', res)

          if (res && res.featureConfig) {
            // 设置草稿名称
            if (res.draftName) {
              that.setData({
                draftName: res.draftName
              })
            }

            // 设置基础头像信息
            if (res.faceBaseId) {
              that.setData({
                avatarId: res.faceBaseId
              })
            }

            // 处理基础脸型信息
            if (res.featureConfig.faceBase) {
              const faceBase = res.featureConfig.faceBase
              that.setData({
                faceBaseUrl: faceBase.imageUrl,
                faceName: faceBase.faceName || '基础脸型'
              })
            }

            // 处理特征数据
            if (res.featureConfig.features && res.featureConfig.features.length > 0) {
              const selectedElements = {}
              const layerPositions = {}
              const layerTransforms = {}

              res.featureConfig.features.forEach(feature => {
                // 根据featureType确定图层类型
                let layerType = 'hair' // 默认为发型
                Object.keys(that.data.layerTypeMap).forEach(key => {
                  if (that.data.layerTypeMap[key] === feature.featureType) {
                    layerType = key
                  }
                })

                // 设置选中的元素
                selectedElements[layerType] = {
                  id: feature.featureId,
                  name: feature.featureName,
                  image: feature.imageUrl,
                  type: feature.featureType
                }

                // 设置位置信息
                layerPositions[layerType] = {
                  x: feature.offsetX,
                  y: feature.offsetY
                }

                // 设置变换信息
                layerTransforms[layerType] = {
                  scale: feature.scale,
                  rotation: feature.rotation
                }
              })

              that.setData({
                selectedElements: selectedElements,
                layerPositions: layerPositions,
                layerTransforms: layerTransforms
              })
            }

            // 加载图层数据
            that.loadLayersData()

            wx.showToast({
              title: '草稿加载成功',
              icon: 'success'
            })
          } else {
            wx.showToast({
              title: '草稿数据格式错误',
              icon: 'none'
            })
          }
        },
        errCallBack: err => {
          console.error('获取草稿详情失败:', err)
          wx.showToast({
            title: '获取草稿详情失败',
            icon: 'none'
          })
        }
      }
      http.request(params)
    } catch (error) {
      console.error('获取草稿详情异常:', error)
      wx.showToast({
        title: '获取草稿详情异常',
        icon: 'none'
      })
    } finally {
      that.setData({ loading: false })
    }
  },

  // 获取人脸底图详情
  getFaceBaseDetail: function (baseId) {
    const that = this
    that.setData({ loading: true })

    try {
      const params = {
        url: '/faceBase/info',
        method: 'GET',
        data: {
          baseId: baseId
        },
        header: {
          'Content-Type': 'application/json'
        },
        callBack: res => {
          console.log('获取人脸底图详情成功:', res)

          if (res) {
            const resourcesUrl = config.resourcesUrl || ''
            const imgUrl = resourcesUrl + (res.faceImageUrl || '/static/images/default-design.png')
            that.setData({
              faceBaseUrl: imgUrl,
              faceName: res.faceName || '基础脸型'
            })
          }
        }
      }
      http.request(params)
    } catch (error) {
      console.error('获取人脸底图失败:', error)
    } finally {
      that.setData({ loading: false })
    }
  },

  // 加载各图层数据
  loadLayersData: function () {
    // 加载所有图层数据
    const layerTypes = ['hair', 'eyes', 'eyesRight', 'eyebrows', 'eyebrowsRight', 'mouth', 'blush', 'blushRight']
    layerTypes.forEach(layerType => {
      this.loadFaceFeatures(layerType)
    })
  },

  // 切换精细控制面板显示/隐藏
  togglePanel: function () {
    this.setData({
      panelCollapsed: !this.data.panelCollapsed
    })
  },

  // 加载五官特征数据
  loadFaceFeatures: function (layerType) {
    const that = this
    const featureType = this.data.layerTypeMap[layerType]

    try {
      const params = {
        url: '/p/faceFeature/page',
        method: 'GET',
        data: {
          page: that.data.currentPage,
          limit: that.data.pageSize,
          featureType: featureType,
          status: 1, // 只获取启用的特征
          sortBy: 'createTime',
          sortOrder: 'desc'
        },
        header: {
          'Content-Type': 'application/json'
        },
        callBack: res => {
          console.log(`获取${layerType}特征数据成功:`, res)

          if (res && res.records && res.records.length > 0) {
            const resourcesUrl = config.resourcesUrl || ''
            const features = res.records.map(item => ({
              featureId: item.featureId, // 保留featureId字段用于选中状态判断
              name: item.featureName || `选项${item.id}`,
              image: resourcesUrl + (item.featureImageUrl || '')
            }))

            // 更新对应图层的数据
            const layers = { ...that.data.layers }
            layers[layerType] = features
            that.setData({ layers })
          } else {
            // 如果没有数据，使用默认的模拟数据
            // that.setDefaultFeatures(layerType)
          }
        }
      }
      http.request(params)
    } catch (error) {
      console.error(`获取${layerType}特征数据失败:`, error)
      // 发生错误时，使用默认的模拟数据
      // that.setDefaultFeatures(layerType)
    }
  },

  // 设置默认的特征数据
  setDefaultFeatures: function (layerType) {
    const defaultImages = ['../../images/icon/design-avatar-1.svg', '../../images/icon/design-avatar-2.svg']
    const defaultFeatures = []

    // 为每个图层生成一些默认选项
    for (let i = 0; i < 4; i++) {
      defaultFeatures.push({
        id: `${layerType}_${i + 1}`,
        name: `${this.getLayerName(layerType)}${i + 1}`,
        image: defaultImages[i % defaultImages.length]
      })
    }

    const layers = { ...this.data.layers }
    layers[layerType] = defaultFeatures
    this.setData({ layers })
  },

  // 获取图层的中文名称
  getLayerName: function (layerType) {
    const layerNames = {
      hair: '发型',
      eyes: '左眼',
      eyesRight: '右眼',
      eyebrows: '左眉',
      eyebrowsRight: '右眉',
      mouth: '嘴巴',
      blush: '左腮红',
      blushRight: '右腮红'
    }
    return layerNames[layerType] || layerType
  },

  // 切换图层
  switchLayer: function (e) {
    const layer = e.currentTarget.dataset.layer
    this.setData({
      currentLayer: layer
    })
  },

  // 进入编辑模式
  enterEditMode: function (e) {
    const layer = e.currentTarget.dataset.layer;
    const element = this.data.selectedElements[layer];

    if (!element || !element.image) {
      console.error('无效的元素数据:', element)
      return
    }

    // 初始化图层位置和变换数据（如果不存在）
    if (!this.data.layerPositions[layer]) {
      this.setData({
        [`layerPositions.${layer}`]: {
          x: 200,
          y: 200
        }
      })
    }

    if (!this.data.layerTransforms[layer]) {
      this.setData({
        [`layerTransforms.${layer}`]: {
          scale: 1,
          rotation: 0
        }
      })
    }

    // 初始化控制点位置（如果不存在）
    if (!this.data.controlPoints[layer]) {
      this.setData({
        [`controlPoints.${layer}`]: {
          center: {
            x: this.data.layerPositions[layer].x || 200,
            y: this.data.layerPositions[layer].y || 200
          },
          scale: {
            x: (this.data.layerPositions[layer].x || 200) + 50,
            y: this.data.layerPositions[layer].y || 200
          },
          rotate: {
            x: this.data.layerPositions[layer].x || 200,
            y: (this.data.layerPositions[layer].y || 200) - 70
          },
          cancel: {
            x: (this.data.layerPositions[layer].x || 200) - 50,
            y: this.data.layerPositions[layer].y || 200
          }
        }
      })
    }

    // 进入编辑模式，并确保面板展开显示
    this.setData({
      editMode: true,
      currentEditingLayer: layer,
      panelCollapsed: false  // 确保点击五官图片时重新显示面板
    })

    console.log(`已进入${layer}图层编辑模式`)
  },

  // 退出编辑模式
  exitEditMode: function () {
    this.setData({
      editMode: false,
      currentEditingLayer: '',
      panelCollapsed: true
    });
  },

  // 选择元素
  selectElement: function (e) {
    console.log(e);

    const { layer, index } = e.currentTarget.dataset
    const element = this.data.layers[layer][index]

    if (!element || !element.image) {
      console.error('无效的元素数据:', element)
      return
    }

    // 初始化图层位置和变换数据（如果不存在）
    if (!this.data.layerPositions[layer]) {
      this.setData({
        [`layerPositions.${layer}`]: {
          x: 0,
          y: 0
        }
      })
    }

    if (!this.data.layerTransforms[layer]) {
      this.setData({
        [`layerTransforms.${layer}`]: {
          scale: 1,
          rotation: 0
        }
      })
    }

    // 初始化控制点位置（如果不存在）
    if (!this.data.controlPoints[layer]) {
      this.setData({
        [`controlPoints.${layer}`]: {
          center: {
            x: 100,
            y: 100
          },
          scale: {
            x: 170,
            y: 170
          },
          rotate: {
            x: 100,
            y: 30
          },
          cancel: {
            x: 30,
            y: 30
          }
        }
      })
    }

    // 更新选中元素
    this.setData({
      [`selectedElements.${layer}`]: element,
      // 进入编辑模式
      editMode: true,
      currentEditingLayer: layer,
      panelCollapsed: false  // 确保选择元素时重新显示面板
    })

    console.log(`已选择${layer}图层元素:`, element)
  },

  // 预览效果
  preview: function () {
    const that = this
    wx.showLoading({
      title: '生成预览中...',
    })

    // 创建canvas上下文
    const ctx = wx.createCanvasContext('previewCanvas', this)

    // 设置Canvas尺寸与设计区域一致
    const canvasWidth = 310  // 与face-container宽度一致
    const canvasHeight = 430  // 与face-container高度一致

    // 清空画布
    ctx.clearRect(0, 0, canvasWidth, canvasHeight)

    // 关键修正：确保Canvas与设计区域布局完全一致
    // face-container: 310px × 430px, 使用flex居中对齐
    // base-face: 280px × 280px

    // 设置白色背景
    ctx.setFillStyle('#000')
    ctx.fillRect(0, 0, canvasWidth, canvasHeight)

    // 下载图片函数
    const downloadImage = (url) => {
      return new Promise((resolve, reject) => {
        if (!url) {
          resolve(null)
          return
        }

        // 检查是否是本地路径
        if (url.startsWith('/images/') || url.startsWith('http://tmp/') || url.startsWith('wxfile://')) {
          resolve(url)
          return
        }

        wx.downloadFile({
          url: url,
          success: (res) => {
            resolve(res.tempFilePath)
          },
          fail: (err) => {
            console.error('下载图片失败:', err)
            reject(err)
          }
        })
      })
    }

    // 获取图片信息
    const getImageInfo = (path) => {
      return new Promise((resolve, reject) => {
        wx.getImageInfo({
          src: path,
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        })
      })
    }

    // 绘制基础头像
    const drawBaseImage = () => {
      return new Promise((resolve) => {
        if (!that.data.faceBaseUrl) {
          resolve()
          return
        }

        downloadImage(that.data.faceBaseUrl)
          .then(async (localPath) => {
            if (localPath) {
              try {
                // 获取原始图片信息以保持宽高比
                const imageInfo = await getImageInfo(localPath)
                const originalWidth = imageInfo.width
                const originalHeight = imageInfo.height
                const originalRatio = originalWidth / originalHeight

                // 设计区域的最大尺寸限制
                const maxSize = 280

                // 根据原始宽高比计算绘制尺寸，保持宽高比
                let drawWidth, drawHeight
                if (originalRatio >= 1) {
                  // 横向图：以宽度为基准
                  drawWidth = maxSize
                  drawHeight = maxSize / originalRatio
                } else {
                  // 纵向图：以高度为基准
                  drawHeight = maxSize
                  drawWidth = maxSize * originalRatio
                }

                // 计算居中位置（在face-container的310px × 430px区域内）
                // 水平居中：(310 - drawWidth) / 2
                const baseX = (310 - drawWidth) / 2
                // 垂直居中：(430 - drawHeight) / 2
                const baseY = (430 - drawHeight) / 2

                ctx.drawImage(localPath, baseX, baseY, drawWidth, drawHeight)
              } catch (err) {
                console.error('获取图片信息失败，使用默认尺寸:', err)
                // 降级处理：使用固定大小
                const baseSize = 280
                const baseX = 15
                const baseY = 75
                ctx.drawImage(localPath, baseX, baseY, baseSize, baseSize)
              }
            }
            resolve()
          })
          .catch(err => {
            console.error('绘制基础头像失败:', err)
            resolve() // 即使失败也继续
          })
      })
    }

    // 按照层级顺序绘制各个图层
    const layerOrder = ['hair', 'eyebrows', 'eyebrowsRight', 'eyes', 'eyesRight', 'blush', 'blushRight', 'mouth']

    // 绘制所有图层
    const drawLayers = async () => {
      // 先绘制基础头像
      await drawBaseImage()

      // 修正：与设计区域完全一致的绘制逻辑
      // 基础头像在Canvas中的位置和中心点
      const baseSize = 280
      const baseX = 15 // 水平居中：(310 - 280) / 2 = 15px
      const baseY = 75 // 垂直居中：(430 - 280) / 2 = 75px
      const baseCenterX = baseX + baseSize / 2  // 155px
      const baseCenterY = baseY + baseSize / 2  // 215px

      // 按顺序绘制各个图层
      for (const layerType of layerOrder) {
        const element = that.data.selectedElements[layerType]
        if (element && element.image) {
          try {
            const localPath = await downloadImage(element.image)
            if (localPath) {
              // 获取图层位置和变换信息
              const position = that.data.layerPositions[layerType]
              const transform = that.data.layerTransforms[layerType]

              // 保存当前上下文状态
              ctx.save()

              // 关键修正：直接使用设计区域的位置坐标
              // 设计区域中，position.x和position.y是相对于face-container左上角的坐标
              // 直接将这些坐标映射到Canvas坐标系
              const layerCenterX = position.x
              const layerCenterY = position.y

              // 设置变换原点到图层中心
              ctx.translate(layerCenterX, layerCenterY)
              console.log(transform, layerType, 'layerCenterX, layerCenterY', layerCenterX, layerCenterY);

              // 应用旋转和缩放变换（与设计区域完全一致）
              ctx.rotate(transform.rotation * Math.PI / 180)
              ctx.scale(transform.scale, transform.scale)

              // 获取图片原始尺寸信息，保持原始比例
              try {
                const imageInfo = await new Promise((resolve, reject) => {
                  wx.getImageInfo({
                    src: localPath,
                    success: resolve,
                    fail: reject
                  })
                })

                console.log(imageInfo, layerType);

                // 使用与设计区域一致的绘制尺寸 - 与WXSS中的layer-image保持一致
                let drawWidth, drawHeight
                let maxSize
                // 特殊处理眼睛图层，使用100*100px的初始尺寸
                if (layerType === 'eyes' || layerType === 'eyesRight' || layerType === 'eyebrows' || layerType === 'eyebrowsRight' || layerType === 'mouth') {
                  maxSize = 100  // 眼睛的初始尺寸为100*100px
                } else if (layerType === 'blush' || layerType === 'blushRight') {
                  maxSize = 120  // 腮红的初始尺寸为120*120px
                } else {
                  maxSize = 240  // 与设计区域中layer-image的尺寸一致
                }
                if (imageInfo.width > imageInfo.height) {
                  // 横向图片
                  drawWidth = maxSize
                  drawHeight = (imageInfo.height / imageInfo.width) * maxSize
                } else {
                  // 纵向图片或正方形
                  drawHeight = maxSize
                  drawWidth = (imageInfo.width / imageInfo.height) * maxSize
                }

                console.log(drawWidth, drawHeight, layerType);

                // 绘制图片（以中心点为基准，保持原始比例）
                ctx.drawImage(localPath, -drawWidth / 2, -drawHeight / 2, drawWidth, drawHeight)
              } catch (err) {
                console.error('获取图片信息失败:', err)
                // 降级处理：使用默认正方形尺寸
                const layerSize = 280
                ctx.drawImage(localPath, -layerSize / 2, -layerSize / 2, layerSize, layerSize)
              }

              // 恢复上下文状态
              ctx.restore()
            }
          } catch (err) {
            console.error(`绘制${layerType}图层失败:`, err)
            // 继续绘制下一个图层
          }
        }
      }

      // 所有图层绘制完成后，生成图片
      ctx.draw(false, () => {
        // 将canvas内容转换为图片
        wx.canvasToTempFilePath({
          canvasId: 'previewCanvas',
          success: function (res) {
            wx.hideLoading()
            console.log(res.tempFilePath);
            // 保存图片到相册
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function () {
                wx.showToast({
                  title: '图片已保存到相册',
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: function (err) {
                console.error('保存图片失败:', err)

                // 检查是否是用户拒绝授权
                if (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied')) {
                  wx.showModal({
                    title: '提示',
                    content: '需要您授权保存图片到相册',
                    confirmText: '去授权',
                    success: function (modalRes) {
                      if (modalRes.confirm) {
                        wx.openSetting({
                          success: function (settingRes) {
                            if (settingRes.authSetting['scope.writePhotosAlbum']) {
                              // 用户授权了，再次尝试保存
                              wx.saveImageToPhotosAlbum({
                                filePath: res.tempFilePath,
                                success: function () {
                                  wx.showToast({
                                    title: '图片已保存到相册',
                                    icon: 'success',
                                    duration: 2000
                                  })
                                },
                                fail: function (err) {
                                  console.error('再次保存图片失败:', err)
                                  wx.showToast({
                                    title: '保存失败',
                                    icon: 'none',
                                    duration: 2000
                                  })
                                }
                              })
                            }
                          }
                        })
                      }
                    }
                  })
                } else {
                  wx.showToast({
                    title: '保存失败',
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          },
          fail: function (err) {
            wx.hideLoading()
            console.error('生成预览图片失败:', err)
            wx.showToast({
              title: '生成预览失败',
              icon: 'none',
              duration: 2000
            })
          }
        }, this)
      })
    }

    // 开始绘制
    drawLayers()
  },

  // 帮助
  showHelp: function () {
    wx.showToast({
      title: '使用说明：点击图片进入编辑模式',
      icon: 'none',
      duration: 2000
    })
  },

  // 分享
  shareWork: function () {
    const that = this

    // 显示加载提示
    wx.showLoading({
      title: '生成分享图片中...',
    })

    // 生成预览图片并上传到服务器
    that.generateAndUploadPreview()
      .then(thumbnailUrl => {
        wx.hideLoading()

        if (!thumbnailUrl) {
          wx.showToast({
            title: '生成分享图片失败',
            icon: 'none'
          })
          return
        }

        // 保存图片URL到data中，供分享使用
        that.setData({
          shareImageUrl: thumbnailUrl
        })

        wx.showToast({
          title: '分享图片已生成，点击分享按钮即可分享',
          icon: 'none',
          duration: 2000
        })
      })
      .catch(err => {
        wx.hideLoading()
        console.error('生成分享图片失败:', err)
        wx.showToast({
          title: '生成分享图片失败',
          icon: 'none'
        })
      })
  },

  // 清空当前图层
  clearCurrentLayer: function () {
    const selectedElements = { ...this.data.selectedElements }
    const layerToClear = this.data.currentEditingLayer || this.data.currentLayer
    selectedElements[layerToClear] = null

    this.setData({
      selectedElements
    })
  },

  // 清空所有
  clearAll: function () {
    wx.showModal({
      title: '提示',
      content: '确定要清空所有编辑吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            selectedElements: {
              hair: null,
              eyes: null,
              eyesRight: null,
              eyebrows: null,
              eyebrowsRight: null,
              mouth: null,
              blush: null,
              blushRight: null
            },
            editMode: false,
            currentEditingLayer: null
          })
        }
      }
    })
  },

  // 保存草稿
  saveDraft: function () {
    const that = this

    // 如果是从草稿编辑进来，则更新草稿
    if (that.data.isFromDraft) {
      that.updateDraft()
      return
    }

    // 弹出输入框，让用户输入草稿名称
    wx.showModal({
      title: '保存草稿',
      content: '请输入草稿名称',
      editable: true,
      placeholderText: '我的草稿',
      success: (res) => {
        if (res.confirm) {
          // 获取用户输入的名称，如果为空则使用默认名称
          const draftName = res.content.trim() || '我的草稿'
          that.saveDraftWork(draftName)
        }
      }
    })
  },

  // 更新草稿
  updateDraft: function () {
    const that = this

    // 直接使用当前data中的draftName进行回显
    const currentDraftName = that.data.draftName || '我的草稿'

    // 显示当前草稿名称，并允许编辑
    wx.showModal({
      title: '更新草稿',
      content: that.data.draftName || '我的草稿',
      editable: true,
      placeholderText: currentDraftName,
      success: (modalRes) => {
        if (modalRes.confirm) {
          // 获取用户输入的名称，如果为空则使用原名称
          const draftName = modalRes.content.trim() || currentDraftName
          that.updateDraftWork(draftName)
        }
      }
    })
  },

  // 更新草稿工作
  updateDraftWork: function (draftName) {
    // 复用updateDraftWorkWithStatus方法的逻辑，但将draftStatus改为1
    this.updateDraftWorkWithStatus(draftName || '我的草稿', 1)
  },

  // 保存草稿工作
  saveDraftWork: function (draftName) {
    const that = this

    // 显示保存中提示
    wx.showLoading({
      title: '保存草稿中...',
    })

    // 先生成并上传预览图片
    that.generateAndUploadPreview()
      .then(thumbnailUrl => {
        console.log('上传预览图片成功后的照片:', thumbnailUrl);

        // 更新提示
        wx.showLoading({
          title: '保存草稿中...',
        })

        try {
          // 准备草稿数据，参考api-test.http中的接口格式
          const draftData = {
            draftName: draftName,
            faceBaseId: that.data.avatarId || 3, // 默认值
            featureConfig: that.prepareFeatureConfig(),
            thumbnailUrl: thumbnailUrl, // 使用上传后的图片URL
            draftStatus: 1 // 1表示草稿状态
          }
          console.log('保存草稿数据:', draftData);

          const params = {
            url: '/p/faceDraft/save',
            method: 'POST',
            data: draftData,
            header: {
              'Content-Type': 'application/json',
            },
            callBack: res => {
              wx.hideLoading()
              console.log('保存草稿成功:', res)
              wx.showToast({
                title: '草稿保存成功',
                icon: 'success',
                duration: 2000
              })
              // 保存成功后返回上一页
              setTimeout(() => {
                wx.navigateBack()
              }, 2000)
            },
            errorCallBack: err => {
              wx.hideLoading()
              console.error('保存草稿失败:', err)
              wx.showToast({
                title: '草稿保存失败，请重试',
                icon: 'none'
              })
            }
          }

          http.request(params)
        } catch (error) {
          wx.hideLoading()
          console.error('保存草稿异常:', error)
          wx.showToast({
            title: '草稿保存异常，请重试',
            icon: 'none'
          })
        }
      })
      .catch(err => {
        wx.hideLoading()
        wx.showToast({
          title: '生成预览图片失败，请重试',
          icon: 'none'
        })
        console.error('生成预览图片失败:', err)
      })
  },

  // 将草稿更新为设计稿
  updateDraftToDesign: function () {
    const that = this
    
    // 显示更新中提示
    wx.showModal({
      title: '更新设计稿',
      content: that.data.draftName || '我的设计稿',
      editable: true,
      placeholderText: that.data.draftName || '我的设计稿',
      success: (res) => {
        if (res.confirm) {
          // 获取用户输入的名称，如果为空则使用当前草稿名称
          const draftName = res.content.trim() || that.data.draftName || '我的设计稿'
          
          // 复用updateDraftWork方法的逻辑，但将draftStatus改为2
          that.updateDraftWorkWithStatus(draftName, 2)
        }
      }
    })
  },

  // 更新草稿工作（可指定状态）
  updateDraftWorkWithStatus: function (draftName, draftStatus) {
    const that = this

    // 显示更新中提示
    wx.showLoading({
      title: draftStatus === 2 ? '更新设计稿中...' : '更新草稿中...',
    })

    // 先生成并上传预览图片
    that.generateAndUploadPreview()
      .then(thumbnailUrl => {
        console.log('上传预览图片成功后的照片:', thumbnailUrl);

        // 更新提示
        wx.showLoading({
          title: draftStatus === 2 ? '更新设计稿中...' : '更新草稿中...',
        })

        try {
          // 准备草稿数据
          const draftData = {
            draftId: that.data.currentDraftId,
            draftName: draftName,
            faceBaseId: that.data.avatarId || 3,
            featureConfig: that.prepareFeatureConfig(),
            thumbnailUrl: thumbnailUrl,
            draftStatus: draftStatus
          }
          console.log('更新数据:', draftData);

          const params = {
            url: '/p/faceDraft/update',
            method: 'PUT',
            data: draftData,
            header: {
              'Content-Type': 'application/json',
            },
            callBack: res => {
              wx.hideLoading()
              console.log('更新成功:', res)
              wx.showToast({
                title: draftStatus === 2 ? '设计稿更新成功' : '草稿更新成功',
                icon: 'success',
                duration: 2000
              })
              // 更新成功后返回上一页
              setTimeout(() => {
                wx.navigateBack()
              }, 2000)
            },
            errorCallBack: err => {
              wx.hideLoading()
              console.error('更新失败:', err)
              wx.showToast({
                title: draftStatus === 2 ? '设计稿更新失败，请重试' : '草稿更新失败，请重试',
                icon: 'none'
              })
            }
          }

          http.request(params)
        } catch (error) {
          wx.hideLoading()
          console.error('更新异常:', error)
          wx.showToast({
            title: draftStatus === 2 ? '设计稿更新异常，请重试' : '草稿更新异常，请重试',
            icon: 'none'
          })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('生成预览图片失败:', err)

        // 即使预览图片生成失败，也继续更新，但使用基础头像作为缩略图
        wx.showLoading({
          title: draftStatus === 2 ? '更新设计稿中...' : '更新草稿中...',
        })

        try {
          const draftData = {
            draftId: that.data.currentDraftId,
            draftName: draftName,
            faceBaseId: that.data.avatarId || 3,
            featureConfig: that.prepareFeatureConfig(),
            thumbnailUrl: that.data.faceBaseUrl,
            draftStatus: draftStatus
          }

          const params = {
            url: '/p/faceDraft/update',
            method: 'PUT',
            data: draftData,
            header: {
              'Content-Type': 'application/json',
            },
            callBack: res => {
              wx.hideLoading()
              if (res && res.code === 0) {
                wx.showToast({
                  title: draftStatus === 2 ? '设计稿更新成功' : '草稿更新成功',
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(() => {
                  wx.navigateBack()
                }, 2000)
              } else {
                wx.showToast({
                  title: res.msg || (draftStatus === 2 ? '设计稿更新失败' : '草稿更新失败'),
                  icon: 'none'
                })
              }
            },
            errorCallBack: err => {
              wx.hideLoading()
              wx.showToast({
                title: draftStatus === 2 ? '设计稿更新失败，请重试' : '草稿更新失败，请重试',
                icon: 'none'
              })
            }
          }

          http.request(params)
        } catch (error) {
          wx.hideLoading()
          wx.showToast({
            title: draftStatus === 2 ? '设计稿更新异常，请重试' : '草稿更新异常，请重试',
            icon: 'none'
          })
        }
      })
  },



  // 生成预览图片并上传到服务器
  generateAndUploadPreview: function () {
    const that = this

    return new Promise((resolve, reject) => {
      // 生成预览图片
      that.generatePreviewImage()
        .then(tempFilePath => {
          // 上传图片到服务器
          that.uploadImageToServer(tempFilePath)
            .then(serverUrl => {
              console.log('上传图片成功:', serverUrl)
              resolve(serverUrl)
            })
            .catch(err => {
              console.error('上传图片失败:', err)
              reject(err)
            })
        })
        .catch(err => {
          console.error('生成预览图片失败:', err)
          reject(err)
        })
    })
  },

  // 完成作品
  completeWork: function () {
    const that = this

    // 检查是否至少选择了一个元素
    const hasSelectedElements = Object.values(that.data.selectedElements).some(element => element !== null)

    if (!hasSelectedElements) {
      wx.showModal({
        title: '提示',
        content: '您还没有选择任何元素，确定要保存空白设计稿吗？',
        success: (modalRes) => {
          if (modalRes.confirm) {
            if (that.data.isFromDraft) {
              that.updateDraftToDesign()
            } else {
              that.showSaveDialog()
            }
          }
        }
      })
    } else {
      // 已有选择的元素，根据是否来自草稿执行不同操作
      if (that.data.isFromDraft) {
        that.updateDraftToDesign()
      } else {
        that.showSaveDialog()
      }
    }
  },

  // 显示保存对话框
  showSaveDialog: function () {
    const that = this

    // 弹出输入框，让用户输入设计稿名称
    wx.showModal({
      title: '保存设计稿',
      content: '请输入设计稿名称',
      editable: true,
      placeholderText: '我的定制头像',
      success: (res) => {
        if (res.confirm) {
          // 获取用户输入的名称，如果为空则使用默认名称
          const draftName = res.content.trim() || '我的定制头像'
          that.saveDesignWork(draftName)
        }
      }
    })
  },

  // 保存设计稿
  saveDesignWork: function (draftName) {
    const that = this

    // 显示保存中提示
    wx.showLoading({
      title: '生成预览中...',
    })

    // 先生成并上传预览图片
    that.generateAndUploadPreview()
      .then(thumbnailUrl => {
        console.log('上传预览图片成功后的照片:', thumbnailUrl);

        // 更新提示
        wx.showLoading({
          title: '保存中...',
        })

        try {
          // 准备保存数据
          const saveData = {
            draftName: draftName,
            faceBaseId: that.data.avatarId || 3, // 默认值
            featureConfig: that.prepareFeatureConfig(),
            thumbnailUrl: thumbnailUrl, // 使用上传后的图片URL
            isPublic: 1,
            viewCount: 0,
            likeCount: 0,
            draftStatus: 2 // 2表示设计稿
          }
          console.log('保存数据:', saveData);

          const params = {
            url: '/p/faceDraft/save',
            method: 'POST',
            data: saveData,
            header: {
              'Content-Type': 'application/json',
            },
            callBack: res => {
              wx.hideLoading()
              console.log('保存设计稿成功:', res)

              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
              // 保存成功后返回上一页
              setTimeout(() => {
                wx.redirectTo({
                  url: '/pages/design/list',
                })
              }, 2000)

            },
            errorCallBack: err => {
              wx.hideLoading()
              console.error('保存设计稿失败:', err)
              wx.showToast({
                title: '保存失败，请重试',
                icon: 'none'
              })
            }
          }

          http.request(params)
        } catch (error) {
          wx.hideLoading()
          console.error('保存设计稿异常:', error)
          wx.showToast({
            title: '保存异常，请重试',
            icon: 'none'
          })
        }
      })
      .catch(err => {
        wx.hideLoading()
        console.error('生成预览图片失败:', err)

        // 即使预览图片生成失败，也继续保存设计稿，但使用基础头像作为缩略图
        wx.showLoading({
          title: '保存中...',
        })

        try {
          const saveData = {
            draftName: draftName,
            faceBaseId: that.data.avatarId || 3,
            featureConfig: that.prepareFeatureConfig(),
            thumbnailUrl: that.data.faceBaseUrl, // 使用基础头像作为缩略图
            designStatus: 1,
            isPublic: 1,
            viewCount: 0,
            likeCount: 0
          }

          const params = {
            url: '/p/faceDesign/save',
            method: 'POST',
            data: saveData,
            header: {
              'Content-Type': 'application/json',
            },
            callBack: res => {
              wx.hideLoading()
              if (res && res.code === 0) {
                wx.showToast({
                  title: '保存成功',
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(() => {
                  wx.navigateBack()
                }, 2000)
              } else {
                wx.showToast({
                  title: res.msg || '保存失败',
                  icon: 'none'
                })
              }
            },
            errorCallBack: err => {
              wx.hideLoading()
              wx.showToast({
                title: '保存失败，请重试',
                icon: 'none'
              })
            }
          }

          http.request(params)
        } catch (error) {
          wx.hideLoading()
          wx.showToast({
            title: '保存异常，请重试',
            icon: 'none'
          })
        }
      })
  },

  // 生成预览图片并上传到服务器
  generateAndUploadPreview: function () {
    const that = this

    return new Promise((resolve, reject) => {
      // 生成预览图片
      that.generatePreviewImage()
        .then(tempFilePath => {
          // 上传图片到服务器
          that.uploadImageToServer(tempFilePath)
            .then(serverUrl => {
              console.log('上传图片成功:', serverUrl)
              resolve(serverUrl)
            })
            .catch(err => {
              console.error('上传图片失败:', err)
              reject(err)
            })
        })
        .catch(err => {
          console.error('生成预览图片失败:', err)
          reject(err)
        })
    })
  },

  // 生成预览图片
  generatePreviewImage: function () {
    const that = this

    return new Promise((resolve, reject) => {
      // 创建canvas上下文
      const ctx = wx.createCanvasContext('previewCanvas', this)

      // 设置Canvas尺寸与设计区域一致
      const canvasWidth = 310  // 与face-container宽度一致
      const canvasHeight = 430  // 与face-container高度一致

      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight)

      // 设置白色背景
      ctx.setFillStyle('#000')
      ctx.fillRect(0, 0, canvasWidth, canvasHeight)

      // 下载图片函数
      const downloadImage = (url) => {
        return new Promise((resolve, reject) => {
          if (!url) {
            resolve(null)
            return
          }

          // 检查是否是本地路径
          if (url.startsWith('/images/') || url.startsWith('http://tmp/') || url.startsWith('wxfile://')) {
            resolve(url)
            return
          }

          wx.downloadFile({
            url: url,
            success: (res) => {
              resolve(res.tempFilePath)
            },
            fail: (err) => {
              console.error('下载图片失败:', err)
              reject(err)
            }
          })
        })
      }

      // 获取图片信息
      const getImageInfo = (path) => {
        return new Promise((resolve, reject) => {
          wx.getImageInfo({
            src: path,
            success: (res) => resolve(res),
            fail: (err) => reject(err)
          })
        })
      }

      // 绘制基础头像
      const drawBaseImage = () => {
        return new Promise((resolve) => {
          if (!that.data.faceBaseUrl) {
            resolve()
            return
          }

          downloadImage(that.data.faceBaseUrl)
            .then(async (localPath) => {
              if (localPath) {
                try {
                  // 获取原始图片信息以保持宽高比
                  const imageInfo = await getImageInfo(localPath)
                  const originalWidth = imageInfo.width
                  const originalHeight = imageInfo.height
                  const originalRatio = originalWidth / originalHeight

                  // 设计区域的最大尺寸限制
                  const maxSize = 280

                  // 根据原始宽高比计算绘制尺寸，保持宽高比
                  let drawWidth, drawHeight
                  if (originalRatio >= 1) {
                    // 横向图：以宽度为基准
                    drawWidth = maxSize
                    drawHeight = maxSize / originalRatio
                  } else {
                    // 纵向图：以高度为基准
                    drawHeight = maxSize
                    drawWidth = maxSize * originalRatio
                  }

                  // 计算居中位置（在face-container的310px × 430px区域内）
                  const baseX = (310 - drawWidth) / 2
                  const baseY = (430 - drawHeight) / 2

                  ctx.drawImage(localPath, baseX, baseY, drawWidth, drawHeight)
                } catch (err) {
                  console.error('获取图片信息失败，使用默认尺寸:', err)
                  // 降级处理：使用固定大小
                  const baseSize = 280
                  const baseX = 15
                  const baseY = 75
                  ctx.drawImage(localPath, baseX, baseY, baseSize, baseSize)
                }
              }
              resolve()
            })
            .catch(err => {
              console.error('绘制基础头像失败:', err)
              resolve() // 即使失败也继续
            })
        })
      }

      // 按照层级顺序绘制各个图层
      const layerOrder = ['hair', 'eyebrows', 'eyebrowsRight', 'eyes', 'eyesRight', 'blush', 'blushRight', 'mouth']

      // 绘制所有图层
      const drawLayers = async () => {
        // 先绘制基础头像
        await drawBaseImage()

        // 基础头像在Canvas中的位置和中心点
        const baseSize = 280
        const baseX = 15 // 水平居中：(310 - 280) / 2 = 15px
        const baseY = 75 // 垂直居中：(430 - 280) / 2 = 75px
        const baseCenterX = baseX + baseSize / 2  // 155px
        const baseCenterY = baseY + baseSize / 2  // 215px

        // 按顺序绘制各个图层
        for (const layerType of layerOrder) {
          const element = that.data.selectedElements[layerType]
          if (element && element.image) {
            try {
              const localPath = await downloadImage(element.image)
              if (localPath) {
                // 获取图层位置和变换信息
                const position = that.data.layerPositions[layerType]
                const transform = that.data.layerTransforms[layerType]

                // 保存当前上下文状态
                ctx.save()

                // 直接使用设计区域的位置坐标
                const layerCenterX = position.x
                const layerCenterY = position.y

                // 设置变换原点到图层中心
                ctx.translate(layerCenterX, layerCenterY)

                // 应用旋转和缩放变换
                ctx.rotate(transform.rotation * Math.PI / 180)
                ctx.scale(transform.scale, transform.scale)

                // 获取图片原始尺寸信息，保持原始比例
                try {
                  const imageInfo = await new Promise((resolve, reject) => {
                    wx.getImageInfo({
                      src: localPath,
                      success: resolve,
                      fail: reject
                    })
                  })

                  // 使用与设计区域一致的绘制尺寸
                  let drawWidth, drawHeight
                  let maxSize
                  // 特殊处理眼睛图层，使用100*100px的初始尺寸
                  if (layerType === 'eyes' || layerType === 'eyesRight' || layerType === 'eyebrows' || layerType === 'eyebrowsRight' || layerType === 'mouth') {
                    maxSize = 100  // 眼睛的初始尺寸为100*100px
                  } else if (layerType === 'blush' || layerType === 'blushRight') {
                    maxSize = 120  // 腮红的初始尺寸为120*120px
                  } else {
                    maxSize = 240  // 与设计区域中layer-image的尺寸一致
                  }
                  if (imageInfo.width > imageInfo.height) {
                    // 横向图片
                    drawWidth = maxSize
                    drawHeight = (imageInfo.height / imageInfo.width) * maxSize
                  } else {
                    // 纵向图片或正方形
                    drawHeight = maxSize
                    drawWidth = (imageInfo.width / imageInfo.height) * maxSize
                  }

                  // 绘制图片（以中心点为基准，保持原始比例）
                  ctx.drawImage(localPath, -drawWidth / 2, -drawHeight / 2, drawWidth, drawHeight)
                } catch (err) {
                  console.error('获取图片信息失败:', err)
                  // 降级处理：使用默认正方形尺寸
                  const layerSize = 280
                  ctx.drawImage(localPath, -layerSize / 2, -layerSize / 2, layerSize, layerSize)
                }

                // 恢复上下文状态
                ctx.restore()
              }
            } catch (err) {
              console.error(`绘制${layerType}图层失败:`, err)
              // 继续绘制下一个图层
            }
          }
        }

        // 所有图层绘制完成后，生成图片
        ctx.draw(false, () => {
          // 将canvas内容转换为图片
          wx.canvasToTempFilePath({
            canvasId: 'previewCanvas',
            success: function (res) {
              resolve(res.tempFilePath)
            },
            fail: function (err) {
              console.error('生成预览图片失败:', err)
              reject(err)
            }
          }, this)
        })
      }

      // 开始绘制
      drawLayers()
    })
  },

  // 上传图片到服务器
  uploadImageToServer: function (tempFilePath) {
    const that = this

    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${config.adminDomain}/admin/file/upload/element`,
        filePath: tempFilePath,
        name: 'file',
        header: {
          'Authorization': wx.getStorageSync('token') || '5045741a-2081-4eda-b092-b976c02c4d99'
        },
        success: (uploadRes) => {
          try {
            const data = JSON.parse(uploadRes.data)
            console.log('上传预览图片成功:', data)

            if (data && data.code === '00000' && data.data) {
              resolve(config.resourcesUrl + data.data)
            } else {
              console.error('上传预览图片返回数据格式错误:', data)
              reject(new Error('上传预览图片返回数据格式错误'))
            }
          } catch (e) {
            console.error('解析上传预览图片返回数据失败:', e)
            reject(e)
          }
        },
        fail: (err) => {
          console.error('上传预览图片失败:', err)
          reject(err)
        }
      })
    })
  },

  // 准备特征配置数据
  prepareFeatureConfig: function () {
    const that = this
    const resourcesUrl = config.resourcesUrl || ''

    // 准备faceBase数据
    const faceBase = {
      faceBaseId: that.data.avatarId || 0,
      faceName: that.data.faceName || '基础脸型',
      imageUrl: that.data.faceBaseUrl || '',
      faceType: 3,
      scale: 1.0,
      offsetX: 0,
      offsetY: 0,
      rotation: 0.0
    }

    // 准备features数据
    const features = []
    let layerOrder = 1
    Object.keys(that.data.selectedElements).forEach(layerType => {
      const element = that.data.selectedElements[layerType]
      console.log('当前图层类型:', layerType);
      console.log('当前元素:', element);

      if (element) {
        const featureType = that.data.layerTypeMap[layerType]

        // 获取当前图层的位置和变换数据
        const position = that.data.layerPositions[layerType] || { x: 0, y: 0 };
        const transform = that.data.layerTransforms[layerType] || { scale: 1.0, rotation: 0.0 };

        features.push({
          configId: Math.random().toString(36).substring(2, 10),
          featureId: element.featureId,
          featureName: element.name,
          featureType: featureType,
          imageUrl: element.image,
          offsetX: position.x,
          offsetY: position.y,
          scale: transform.scale,
          rotation: transform.rotation,
          layerOrder: layerOrder++,
          visible: true,
          opacity: 1.0,
          blendMode: 'normal',
          filter: {
            brightness: 0,
            contrast: 0,
            saturation: 0,
            hue: 0,
            blur: 0,
            grayscale: false,
            invert: false
          }
        })
      }
    })

    // 准备canvas数据
    const canvas = {
      width: 800,
      height: 600,
      backgroundColor: '#000',
      backgroundImage: '',
      zoom: 1.0,
      panX: 0,
      panY: 0
    }

    // 准备metadata数据
    const now = new Date()
    const metadata = {
      version: '1.0',
      createTime: now.toLocaleString('zh-CN'),
      lastModified: now.toLocaleString('zh-CN'),
      author: 'user',
      tags: ['定制', '头像'],
      description: '自定义头像设计稿',
      thumbnailUrl: that.data.faceBaseUrl || ''
    }

    return {
      faceBase,
      features,
      canvas,
      metadata
    }
  },

  // 重新开始
  restart: function () {
    wx.showModal({
      title: '提示',
      content: '确定要重新开始吗？',
      success: (res) => {
        if (res.confirm) {
          this.clearAll()
        }
      }
    })
  },

  /**
   * 获取对称图层
   * @param {string} layer - 当前图层
   * @returns {string|null} - 对称图层名称
   */
  getSymmetricLayer(layer) {
    const symmetricLayers = {
      'eyes': 'eyesRight', // 左眼 -> 右眼
      'eyesRight': 'eyes', // 右眼 -> 左眼
      'eyebrows': 'eyebrowsRight', // 左眉 -> 右眉
      'eyebrowsRight': 'eyebrows', // 右眉 -> 左眉
      'blush': 'blushRight', // 左腮红 -> 右腮红
      'blushRight': 'blush' // 右腮红 -> 左腮红
    };
    
    return symmetricLayers[layer] || null;
  },

  /**
   * 触摸开始事件
   */
  onTouchStart(e) {
    const { target, touches, currentTarget } = e;
    console.log('触摸开始事件:', e);

    const touch = touches[0];
    const layer = this.data.currentEditingLayer;
    const { controlPoints, layerPositions } = this.data;

    // 判断触摸点类型 - 使用currentTarget.id代替target.id，因为微信小程序中image元素的target可能为空
    let elementId = '';

    // 尝试从currentTarget获取ID
    if (currentTarget && currentTarget.id) {
      elementId = currentTarget.id;
    }
    // 如果currentTarget没有ID，尝试从target获取
    else if (target && target.id) {
      elementId = target.id;
    }

    // 检查是否是控制点
    if (layer && elementId === `${layer}-scale`) {
      // 缩放点 - 仅缩放
      this.setData({
        touchType: 'scale',
        startX: touch.clientX,
        startY: touch.clientY,
        startDistance: Math.sqrt(Math.pow(controlPoints[layer].center.x - controlPoints[layer].scale.x, 2) + Math.pow(controlPoints[layer].center.y - controlPoints[layer].scale.y, 2))
      });
    } else if (layer && elementId === `${layer}-rotate`) {
      // 旋转点 - 仅旋转
      this.setData({
        touchType: 'rotate',
        startX: touch.clientX,
        startY: touch.clientY,
        startAngle: Math.atan2(controlPoints[layer].center.y - controlPoints[layer].rotate.y, controlPoints[layer].center.x - controlPoints[layer].rotate.x)
      });
    } else if (layer && elementId === `${layer}-cancel`) {
      // 取消点 - 删除当前选中的五官
      const that = this;
      
      // 显示确认对话框
      wx.showModal({
        title: '确认删除',
        content: '确定要删除当前选中的五官吗？',
        success: function(res) {
          if (res.confirm) {
            // 用户确认删除
            console.log('删除五官:', layer);
            
            // 清除选中的五官
            that.setData({
              [`selectedElements.${layer}`]: null,
              editMode: false,
              currentEditingLayer: null
            });
            
            wx.showToast({
              title: '已删除',
              icon: 'success',
              duration: 1500
            });
          } else {
            // 用户取消删除，只退出编辑模式
            that.setData({
              editMode: false,
              currentEditingLayer: null
            });
          }
        }
      });
    } else if (currentTarget && currentTarget.dataset && currentTarget.dataset.action === 'drag') {
      // 直接拖动五官元素
      const targetLayer = currentTarget.dataset.layer;

      // 如果没有当前编辑图层，或者点击的是不同的图层，则设置当前编辑图层
      if (!layer || layer !== targetLayer) {
        this.setData({
          editMode: true,
          currentEditingLayer: targetLayer,
          panelCollapsed: false  // 确保拖动五官图片时重新显示面板
        });
      }

      // 设置拖动状态
      this.setData({
        touchType: 'drag',
        startX: touch.clientX - (layerPositions[targetLayer] ? layerPositions[targetLayer].x : 0),
        startY: touch.clientY - (layerPositions[targetLayer] ? layerPositions[targetLayer].y : 0)
      });
    } else {
      // 如果没有匹配到任何控制点，且当前有编辑图层，则认为是拖动图层
      if (layer && layerPositions[layer]) {
        this.setData({
          touchType: 'drag',
          startX: touch.clientX - layerPositions[layer].x,
          startY: touch.clientY - layerPositions[layer].y
        });
      }
    }
  },

  /**
   * 触摸移动事件
   */
  onTouchMove(e) {
    const { target, touches, currentTarget } = e;
    const touch = touches[0];
    const layer = this.data.currentEditingLayer;
    const { touchType } = this.data;

    if (!layer || !touchType) return;

    const { layerPositions, layerTransforms, controlPoints } = this.data;
    const { center, scale, rotate, cancel } = controlPoints[layer];

    if (touchType === 'drag') {
      // 拖动中心点
      const newX = touch.clientX - this.data.startX;
      const newY = touch.clientY - this.data.startY;

      // 获取对称图层
      const symmetricLayer = this.getSymmetricLayer(layer);
      
      // 计算中心点，用于对称计算
      const centerX = 155; // 脸部中心X坐标
      
      // 更新当前图层位置
      this.setData({
        [`layerPositions.${layer}.x`]: newX,
        [`layerPositions.${layer}.y`]: newY,
        [`controlPoints.${layer}.center.x`]: newX,
        [`controlPoints.${layer}.center.y`]: newY,
        [`controlPoints.${layer}.scale.x`]: newX + 50,
        [`controlPoints.${layer}.scale.y`]: newY,
        [`controlPoints.${layer}.rotate.x`]: newX,
        [`controlPoints.${layer}.rotate.y`]: newY - 70,
        [`controlPoints.${layer}.cancel.x`]: newX - 50,
        [`controlPoints.${layer}.cancel.y`]: newY
      });
      
      // 如果存在对称图层，则同步更新对称图层
      if (symmetricLayer && this.data.layerPositions[symmetricLayer]) {
        // 计算对称位置
        // X轴：对称位置 = 中心点 * 2 - 当前位置
        const symmetricX = centerX * 2 - newX;
        // Y轴：保持相同
        const symmetricY = newY;
        
        // 更新对称图层位置
        this.setData({
          [`layerPositions.${symmetricLayer}.x`]: symmetricX,
          [`layerPositions.${symmetricLayer}.y`]: symmetricY,
          [`controlPoints.${symmetricLayer}.center.x`]: symmetricX,
          [`controlPoints.${symmetricLayer}.center.y`]: symmetricY,
          [`controlPoints.${symmetricLayer}.scale.x`]: symmetricX + 50,
          [`controlPoints.${symmetricLayer}.scale.y`]: symmetricY,
          [`controlPoints.${symmetricLayer}.rotate.x`]: symmetricX,
          [`controlPoints.${symmetricLayer}.rotate.y`]: symmetricY - 70,
          [`controlPoints.${symmetricLayer}.cancel.x`]: symmetricX - 50,
          [`controlPoints.${symmetricLayer}.cancel.y`]: symmetricY
        });
      }
    } else if (touchType === 'scale') {
      // 仅缩放操作 - 向右下拖动放大，向左上拖动缩小
      const deltaX = touch.clientX - this.data.startX;
      const deltaY = touch.clientY - this.data.startY;

      // 计算拖动方向和距离
      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);

      // 根据拖动方向确定缩放方向
      // 向右下拖动（deltaX > 0 && deltaY > 0）为放大
      // 向左上拖动（deltaX < 0 && deltaY < 0）为缩小
      // 其他方向根据主要方向判断
      let scaleDirection = 1; // 默认放大

      if (deltaX < 0 && deltaY < 0) {
        // 向左上拖动，缩小
        scaleDirection = -1;
      } else if (deltaX > 0 && deltaY > 0) {
        // 向右下拖动，放大
        scaleDirection = 1;
      } else if (Math.abs(deltaX) > Math.abs(deltaY)) {
        // 水平方向为主
        scaleDirection = deltaX > 0 ? 1 : -1;
      } else {
        // 垂直方向为主
        scaleDirection = deltaY > 0 ? 1 : -1;
      }

      // 计算缩放比例（距离越远，缩放幅度越大）
      const scaleFactor = 1 + (distance / 200) * scaleDirection;
      const newScale = layerTransforms[layer].scale * scaleFactor;

      // 获取对称图层
      const symmetricLayer = this.getSymmetricLayer(layer);

      // 更新当前图层缩放
      this.setData({
        [`layerTransforms.${layer}.scale`]: newScale,
        startX: touch.clientX,
        startY: touch.clientY
      });

      // 更新当前图层缩放控制点位置
      const scaleControlX = center.x + 50 * newScale;
      const scaleControlY = center.y;

      this.setData({
        [`controlPoints.${layer}.scale.x`]: scaleControlX,
        [`controlPoints.${layer}.scale.y`]: scaleControlY
      });
      
      // 如果存在对称图层，则同步更新对称图层的缩放
      if (symmetricLayer && this.data.layerTransforms[symmetricLayer]) {
        // 对称图层使用相同的缩放比例
        this.setData({
          [`layerTransforms.${symmetricLayer}.scale`]: newScale
        });
        
        // 更新对称图层缩放控制点位置
        const symmetricCenter = this.data.controlPoints[symmetricLayer].center;
        const symmetricScaleControlX = symmetricCenter.x + 50 * newScale;
        const symmetricScaleControlY = symmetricCenter.y;
        
        this.setData({
          [`controlPoints.${symmetricLayer}.scale.x`]: symmetricScaleControlX,
          [`controlPoints.${symmetricLayer}.scale.y`]: symmetricScaleControlY
        });
      }
    } else if (touchType === 'rotate') {
      // 仅旋转操作
      const currentAngle = Math.atan2(center.y - touch.clientY, center.x - touch.clientX);

      // 计算旋转角度变化
      const angleDiff = currentAngle - this.data.startAngle;
      const newRotate = (layerTransforms[layer].rotation + angleDiff * 180 / Math.PI) % 360;

      // 获取对称图层
      const symmetricLayer = this.getSymmetricLayer(layer);

      // 更新当前图层旋转
      this.setData({
        [`layerTransforms.${layer}.rotation`]: newRotate,
        startAngle: currentAngle
      });

      // 更新当前图层旋转控制点位置
      const rotateDistance = 70;
      const rotateControlX = center.x + Math.cos(currentAngle) * rotateDistance;
      const rotateControlY = center.y + Math.sin(currentAngle) * rotateDistance;

      this.setData({
        [`controlPoints.${layer}.rotate.x`]: rotateControlX,
        [`controlPoints.${layer}.rotate.y`]: rotateControlY
      });
      
      // 如果存在对称图层，则同步更新对称图层的旋转
      if (symmetricLayer && this.data.layerTransforms[symmetricLayer]) {
        // 对称图层使用相同的旋转角度
        this.setData({
          [`layerTransforms.${symmetricLayer}.rotation`]: newRotate
        });
        
        // 更新对称图层旋转控制点位置
        const symmetricCenter = this.data.controlPoints[symmetricLayer].center;
        // 对称图层的旋转控制点角度需要镜像
        const symmetricAngle = Math.PI - currentAngle;
        const symmetricRotateControlX = symmetricCenter.x + Math.cos(symmetricAngle) * rotateDistance;
        const symmetricRotateControlY = symmetricCenter.y + Math.sin(symmetricAngle) * rotateDistance;
        
        this.setData({
          [`controlPoints.${symmetricLayer}.rotate.x`]: symmetricRotateControlX,
          [`controlPoints.${symmetricLayer}.rotate.y`]: symmetricRotateControlY
        });
      }
    }
  },

  /**
   * 触摸结束事件
   */
  onTouchEnd(e) {
    // 重置触摸状态
    this.setData({
      touchType: null,
      startX: 0,
      startY: 0,
      startAngle: 0,
      startDistance: 0
    });
  },

  /**
   * 移动图层位置
   */
  moveLayer(e) {
    const { direction } = e.currentTarget.dataset;
    const layer = this.data.currentEditingLayer;

    if (!layer) return;

    const moveDistance = 5; // 每次移动的像素距离
    const { layerPositions, controlPoints } = this.data;
    let newX = layerPositions[layer].x;
    let newY = layerPositions[layer].y;

    switch (direction) {
      case 'up':
        newY -= moveDistance;
        break;
      case 'down':
        newY += moveDistance;
        break;
      case 'left':
        newX -= moveDistance;
        break;
      case 'right':
        newX += moveDistance;
        break;
    }

    // 更新图层位置
    this.setData({
      [`layerPositions.${layer}.x`]: newX,
      [`layerPositions.${layer}.y`]: newY,
      [`controlPoints.${layer}.center.x`]: newX,
      [`controlPoints.${layer}.center.y`]: newY,
      [`controlPoints.${layer}.scale.x`]: newX + 50,
      [`controlPoints.${layer}.scale.y`]: newY,
      [`controlPoints.${layer}.rotate.x`]: newX,
      [`controlPoints.${layer}.rotate.y`]: newY - 70,
      [`controlPoints.${layer}.cancel.x`]: newX - 50,
      [`controlPoints.${layer}.cancel.y`]: newY
    });
  },

  /**
   * 重置图层位置
   */
  resetPosition(e) {
    const layer = this.data.currentEditingLayer;

    if (!layer) return;

    // 获取默认位置
    const defaultPositions = {
      hair: { x: 200, y: 180 },
      eyes: { x: 180, y: 150 }, // 左眼
      eyesRight: { x: 220, y: 150 }, // 右眼
      eyebrows: { x: 180, y: 130 }, // 左眉
      eyebrowsRight: { x: 220, y: 130 }, // 右眉
      mouth: { x: 200, y: 200 },
      blush: { x: 170, y: 180 }, // 左腮红
      blushRight: { x: 230, y: 180 } // 右腮红
    };

    const defaultPosition = defaultPositions[layer] || { x: 200, y: 200 };

    // 重置位置和变换
    this.setData({
      [`layerPositions.${layer}.x`]: defaultPosition.x,
      [`layerPositions.${layer}.y`]: defaultPosition.y,
      [`layerTransforms.${layer}.scale`]: 1,
      [`layerTransforms.${layer}.rotation`]: 0,
      [`controlPoints.${layer}.center.x`]: defaultPosition.x,
      [`controlPoints.${layer}.center.y`]: defaultPosition.y,
      [`controlPoints.${layer}.scale.x`]: defaultPosition.x + 50,
      [`controlPoints.${layer}.scale.y`]: defaultPosition.y,
      [`controlPoints.${layer}.rotate.x`]: defaultPosition.x,
      [`controlPoints.${layer}.rotate.y`]: defaultPosition.y - 70,
      [`controlPoints.${layer}.cancel.x`]: defaultPosition.x - 50,
      [`controlPoints.${layer}.cancel.y`]: defaultPosition.y
    });
  },

  /**
   * 旋转图层
   */
  rotateLayer(e) {
    const { direction } = e.currentTarget.dataset;
    const layer = this.data.currentEditingLayer;

    if (!layer) return;

    const rotateAngle = 1; // 每次旋转的角度
    const { layerTransforms } = this.data;
    const currentRotation = layerTransforms[layer].rotation || 0;

    // 计算新旋转角度
    let newRotation;
    if (direction === 'left') {
      newRotation = (currentRotation - rotateAngle + 360) % 360;
    } else {
      newRotation = (currentRotation + rotateAngle) % 360;
    }

    // 更新旋转
    this.setData({
      [`layerTransforms.${layer}.rotation`]: newRotation
    });

    // 更新旋转控制点位置
    const { center } = this.data.controlPoints[layer];
    const rotateDistance = 70;
    const rotateControlX = center.x + Math.cos(newRotation * Math.PI / 180) * rotateDistance;
    const rotateControlY = center.y + Math.sin(newRotation * Math.PI / 180) * rotateDistance;

    this.setData({
      [`controlPoints.${layer}.rotate.x`]: rotateControlX,
      [`controlPoints.${layer}.rotate.y`]: rotateControlY
    });
  },

  /**
   * 缩放图层
   */
  scaleLayer(e) {
    const { action, ratio } = e.currentTarget.dataset;
    const layer = this.data.currentEditingLayer;

    if (!layer) return;

    // 使用传入的缩放比例，如果没有则使用默认值
    const scaleFactor = parseFloat(ratio) || 0.1;
    const { layerTransforms } = this.data;
    const currentScale = layerTransforms[layer].scale || 1;

    // 计算新缩放比例
    let newScale;
    if (action === 'decrease') {
      // 移除最小缩放限制，允许无限缩小
      newScale = currentScale - scaleFactor;
    } else {
      // 保持最大缩放限制，防止过大
      newScale = Math.min(2.0, currentScale + scaleFactor);
    }

    // 更新缩放
    this.setData({
      [`layerTransforms.${layer}.scale`]: newScale
    });

    // 更新缩放控制点位置
    const { center } = this.data.controlPoints[layer];
    const scaleControlX = center.x + 50 * newScale;
    const scaleControlY = center.y;

    this.setData({
      [`controlPoints.${layer}.scale.x`]: scaleControlX,
      [`controlPoints.${layer}.scale.y`]: scaleControlY
    });
  },

  /**
   * 调整图层层级
   */
  adjustLayerZIndex(e) {
    const { direction } = e.currentTarget.dataset;
    const layer = this.data.currentEditingLayer;

    if (!layer) return;

    // 获取当前图层的z-index
    const currentZIndex = this.getCurrentLayerZIndex(layer);

    // 计算新的z-index
    let newZIndex;
    if (direction === 'up') {
      newZIndex = Math.min(100, currentZIndex + 5); // 最大z-index为100
    } else {
      newZIndex = Math.max(1, currentZIndex - 5); // 最小z-index为1
    }

    // 更新图层的z-index
    this.updateLayerZIndex(layer, newZIndex);
  },


  /**
   * 获取当前图层的z-index
   */
  getCurrentLayerZIndex(layer) {
    // 从默认的z-index映射中获取
    const defaultZIndexes = {
      hair: 10,
      eyebrows: 20,
      eyebrowsRight: 20,
      eyes: 30,
      eyesRight: 30,
      mouth: 40,
      blush: 50,
      blushRight: 50
    };

    // 如果已经自定义了z-index，则从自定义数据中获取
    // 这里简化处理，实际应用中可能需要更复杂的状态管理
    return defaultZIndexes[layer] || 10;
  },

  /**
   * 更新图层的z-index
   */
  updateLayerZIndex(layer, newZIndex) {
    // 这里简化处理，实际应用中可能需要更新CSS类或内联样式
    // 由于微信小程序的限制，我们可能需要使用动态类名或内联样式

    // 创建一个临时的z-index映射
    const layerZIndexes = this.data.layerZIndexes || {};
    layerZIndexes[layer] = newZIndex;

    this.setData({
      layerZIndexes
    });

    // 实际应用中，可能需要使用WXS或其他方式动态更新样式
    console.log(`更新${layer}图层的z-index为: ${newZIndex}`);
  },

  /**
   * 分享给朋友
   */
  onShareAppMessage: function () {
    const that = this

    return {
      title: '我设计了一个有趣的人脸娃娃，快来看看吧！',
      path: '/pages/index/index',
      imageUrl: that.data.shareImageUrl || '', // 使用上传服务器返回的图片链接
      success: function (res) {
        // 分享成功
        console.log('分享成功', res)
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        })
      },
      fail: function (res) {
        // 分享失败
        console.log('分享失败', res)
        wx.showToast({
          title: '分享失败',
          icon: 'none'
        })
      }
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline: function () {
    const that = this

    return {
      title: '我设计了一个有趣的人脸娃娃，快来看看吧！',
      query: 'from=timeline',
      imageUrl: that.data.shareImageUrl || '', // 使用上传服务器返回的图片链接
      success: function (res) {
        // 分享成功
        console.log('分享到朋友圈成功', res)
        wx.showToast({
          title: '分享成功',
          icon: 'success'
        })
      },
      fail: function (res) {
        // 分享失败
        console.log('分享到朋友圈失败', res)
        wx.showToast({
          title: '分享失败',
          icon: 'none'
        })
      }
    }
  }
})